import { 
  Component, 
  ElementRef, 
  Input, 
  OnInit, 
  AfterViewInit,
  OnDestroy,
  ViewChild, 
  Renderer2,
  ChangeDetectionStrategy
} from '@angular/core';

export interface ImageSlide {
  id: number;
  imgUrl: string;
  link: string;
  caption: string
}

@Component({
  selector: 'app-image-slide',
  templateUrl: './image-slide.component.html',
  styleUrls: ['./image-slide.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ImageSlideComponent implements OnInit, AfterViewInit, OnDestroy {
  @Input() slides: ImageSlide[] = [];
  @Input() sliderHeight = '160px';
  @Input() intervalBySeconds = 2;
  @ViewChild('imageSlider', {static: true}) imgSlider: ElementRef;
  selectedIndex = 0;
  intervalId;
  constructor(private rd2: Renderer2) { }

  ngOnInit() {
  }

  ngAfterViewInit(): void {
    if(this.intervalBySeconds <= 0) {
      return;
    }
    this.intervalId = setInterval(() => {
      this.rd2.setProperty(
        this.imgSlider.nativeElement, 
        'scrollLeft',
        (this.getIndex(++this.selectedIndex)) * this.imgSlider.nativeElement.scrollWidth / this.slides.length
      )
    }, this.intervalBySeconds * 1000)
  }
  
  ngOnDestroy(): void {
    clearInterval(this.intervalId);
  }

  getIndex (idx: number) : number {
    return idx >= 0 
    ? idx % this.slides.length
    : this.slides.length - (Math.abs(idx) % this.slides.length) 
  }

  handleScroll (ev) {
    const ratio = (ev.target.scrollLeft * this.slides.length) / ev.target.scrollWidth;
    this.selectedIndex = Math.round(ratio); 
  }
}
